import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_fancy_tree_view/flutter_fancy_tree_view.dart';

import '../model/model_user_album.dart';
import '../service/service_user_album.dart';
import '../widget/widget_album.dart';
import 'panel_main_album_media_list.dart';

// 专辑列表面板
class PanelAlbumList extends StatefulWidget {
  const PanelAlbumList({super.key});

  @override
  State<PanelAlbumList> createState() => _PanelAlbumListState();
}

class _PanelAlbumListState extends State<PanelAlbumList> {
  List<ModelUserAlbum> albums = [];
  late final TreeController<TreeNode> treeController;

  List<TreeNode> treeRoots = <TreeNode>[
    TreeNode(title: "需要复习"),
    TreeNode(title: "最近学习"),
    TreeNode(title: "最新添加"),
    TreeNode(title: "所有"),
  ];

  @override
  void initState() {
    super.initState();
    treeController = TreeController(roots: treeRoots, childrenProvider: (TreeNode node) => node.children);
    refreshAlbums();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Row(
        children: [
          // 1. 左侧树
          buildLeftTree(),
          // 2. 有些列表
          buildRightList(),
        ],
      ),
    );
  }

  buildLeftTree() {
    return Container(
        width: 110,
        child: TreeView(
            treeController: treeController,
            nodeBuilder: (BuildContext context, TreeEntry<TreeNode> entry) {
              return TreeTile(
                key: ValueKey(entry.node),
                entry: entry,
                onTap: () {
                  print("onTap");
                  print(entry.node.title);
                  return treeController.toggleExpansion(entry.node);
                },
              );
            }));
  }

  buildRightList() {
    return Expanded(child: Column(children: [buildTools(), buildList()]));
  }

  buildTools() {
    return Container(
        height: 50,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton.icon(
                icon: Icon(Icons.add),
                label: Text("添加专辑"),
                onPressed: () {
                  print("添加专辑");
                  op("op_add_media");
                }),
            SizedBox(
              width: 15,
            ),
            ElevatedButton.icon(
                icon: Icon(Icons.refresh),
                label: Text("刷新"),
                onPressed: () {
                  refreshAlbums();
                }),
          ],
        ));
  }

  buildList() {
    return Expanded(
        child: ListView.builder(
            itemCount: albums.length,
            itemExtent: 50.0, //强制高度为50.0
            itemBuilder: (BuildContext context, int index) {
              String name = albums[index].name!;
              return WidgetAlbum(
                album: albums[index],
                onView: (id) {
                  print(id);
                  Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                    return PanelAlbumMediaList(
                      albumId: id,
                    );
                  }));
                },
                onDelete: (id) {
                  // 删除
                  print("删除${id}");
                  // ServiceUserAlbum.deleteAlbumById(id);
                  // refreshAlbums();

                  _deleteId = id;
                  op("op_delete_media");
                },
              );
            }));
  }

  int type = 0;
  int _deleteId = 0;

  op(String op) {
    if (op == "op_add_media") {
      showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text("添加文件说明"),
              content: Text("1. 选择包含媒体文件的文件夹添加.\n2. 文件夹内应包含媒体文件(MP4、MP3)和字幕文件(.srt)\n3. 本软件会记录文件夹路径，但不会复制。"),
              actions: [
                TextButton(
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                    child: Text("取消添加")),
                TextButton(
                    onPressed: () async {
                      Navigator.of(context).pop();
                      String? selectedDirectory = await FilePicker.platform.getDirectoryPath();
                      if (selectedDirectory != null) {
                        // User canceled the picker
                        print(selectedDirectory);
                        ServiceUserAlbum.addUserAlbum(selectedDirectory);
                        Future.delayed(Duration(milliseconds: 500), () {
                          // 延迟执行的代码
                          refreshAlbums();
                        });
                      }
                    },
                    child: Text("确认添加"))
              ],
            );
          });
    } else if (op == "op_delete_media") {
      showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text("删除说明"),
              content: Text("删除专辑后相关学习记录也会被删除。"),
              actions: [
                TextButton(
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                    child: Text("取消删除")),
                TextButton(
                    onPressed: () async {
                      Navigator.of(context).pop();
                      ServiceUserAlbum.deleteAlbumById(_deleteId);
                      refreshAlbums();
                    },
                    child: Text("确认删除"))
              ],
            );
          });
    }
  }

  void refreshAlbums() {
    // 1.
    if (type == 0) {
      // 查询所有
      albums = ServiceUserAlbum.list();
    } else if (type == 1) {
      // 查询最新添加
      albums = ServiceUserAlbum.list();
    } else if (type == 2) {
      // 查询需要复习
      albums = ServiceUserAlbum.listNeedReview();
    } else if (type == 3) {
      // 最近学习
      albums = ServiceUserAlbum.listLastStudy();
    }
    setState(() {});
  }
}

class TreeTile extends StatelessWidget {
  const TreeTile({super.key, required this.entry, required this.onTap});

  final TreeEntry<TreeNode> entry;
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      child: TreeIndentation(
        entry: entry,
        guide: const IndentGuide.connectingLines(indent: 48),
        child: Padding(
          padding: const EdgeInsets.fromLTRB(4, 5, 5, 5),
          child: Row(
            children: [Text(entry.node.title)],
          ),
        ),
      ),
    );
  }
}

class TreeNode {
  TreeNode({required this.title, this.children = const <TreeNode>[]});

  final String title;
  final List<TreeNode> children;
}
